package top.xin1901.j2ecd.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import top.xin1901.j2ecd.beans.Type;
import top.xin1901.j2ecd.common.response.R;
import top.xin1901.j2ecd.common.util.DataCheck;
import top.xin1901.j2ecd.service.TypeService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author HeYunjia
 */

@RestController
@CrossOrigin("*")
@RequestMapping("/type")
public class TypeController {

    @Resource
    private TypeService typeService;

    @PostMapping
    public R postTypeOne(@RequestBody Type type) {

        if (DataCheck.checkType(type, true)) type = typeService.insertOne(type);
        else return R.fail();

        if (type == null) return R.fail();

        return R.success().add("type", type);
    }

    @DeleteMapping
    public R deleteTypeOne(@RequestBody Type type) {
        // 删除还不能写, 删除应当首先删除该类型的权限, 有外键关联, 需要进行逻辑处理
        return R.success()
                .add("type", type)
                .add("msg", "还没有设计, 还需要考虑同步删除权限");
    }

    @PutMapping
    public R putTypeOne(@RequestBody Type type) {
        if (DataCheck.checkType(type)) type = typeService.updateOne(type);
        else return R.fail();

        if (type == null) return R.fail();

        return R.success().add("type", type);
    }

    @GetMapping
    public R getTypeAll() {
        return R.success()
                .add("types", typeService.selectAll());
    }

    @GetMapping("/{pageNumber}/{pageSize}")
    public R getTypePage(@PathVariable Integer pageNumber,
                         @PathVariable Integer pageSize) {

        PageHelper.startPage(pageNumber, pageSize);
        List<Type> types = typeService.selectAll();

        return R.success()
                .add("page", new PageInfo<>(types));
    }

    @GetMapping("/{typeId}")
    public R getTypeOne(@PathVariable Long typeId) {
        Type type = typeService.selectOne(typeId);

        if (type == null) return R.fail();

        return R.success().add("type", type);
    }




}
